package com.yonyou.le.unattended.websocket.hardware;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.google.gson.Gson;

public class WSConCache {

	public static Map<String,WebSocketSession> hardwareMap = new ConcurrentHashMap<>();
	
	public static void putSession(WebSocketSession wss){
		String clientid = wss.getId();
		if(!hardwareMap.containsKey(clientid)){
			hardwareMap.put(clientid, wss);
		}
	}
	
	
	public static void removeSession(String clientid){
		hardwareMap.remove(clientid);
	}
	
	public static void sendMessage(String clientid,String data){
		WebSocketSession wss = hardwareMap.get(clientid);
		
		Gson gson = new Gson();
		
		if (wss.isOpen()) {
			try {
				wss.sendMessage(new TextMessage(gson.toJson(data).getBytes("utf-8")));
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	}
	
}
